﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data.Sql;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Modify : System.Web.UI.Page
{
    protected void Page_PreRender(object sender, EventArgs e)
    {
        //// load the data for the selected item
        //// this has to be done in Pag_PreRender because
        //// the click event of the Save button is not executed until after
        //// the Page_Load event. >.<

        string connectionString =
                WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        if (Session["SelectedId"] != null)
        {
            string creator = String.Empty;
            string label = String.Empty;
            string category = String.Empty;
            string categoryId = String.Empty;
            string priority = String.Empty;
            string assignee = String.Empty;
            string description = String.Empty;
            string statusCode = String.Empty;
            DateTime createdDate;
            string resolvedDate = String.Empty;

            int selectedId = (int)Session["SelectedId"];

            SqlConnection con = new SqlConnection(connectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * from vwGetIssues WHERE [Issue Id] = " + selectedId.ToString();

            using (con)
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    creator = reader["Creator"].ToString();
                    label = reader["FullLabel"].ToString();
                    category = reader["Category"].ToString();
                    categoryId = reader["Category Id"].ToString();
                    priority = reader["Priority"].ToString();
                    assignee = reader["Assigned To"].ToString();
                    description = reader["Description"].ToString();
                    statusCode = reader["status_code"].ToString();
                    createdDate = Convert.ToDateTime(reader["Created On"]);

                    // A status code of 3 means that the issue has been resolved
                    if (statusCode == "3")
                    {
                        resolvedDate = String.Format("{0:d}", reader["Resolved On"]);
                    }
                }
            }

            lblDisplayId.Text = selectedId.ToString();
            lblDisplayCreator.Text = creator;
            lblDisplayLabel.Text = label;
            txtDescription.Text = description;
            txtDateResolved.Text = resolvedDate;

            // set the selected values of the bound drop down lists
            ddlCategory.SelectedValue = categoryId;
            ddlPriority.SelectedValue = priority;
            ddlAssigned.SelectedValue = assignee;
            ddlStatus.SelectedValue = statusCode;

            // append the label of the issue to the page's title
            Page.Title += " - " + label;
        }
        else
        {
            Response.Redirect("~/View.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        lblErrorStatus.Visible = true;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        Validate();

        if (Page.IsValid)
        {
            int issueId = Convert.ToInt32(lblDisplayId.Text);
            string creator = lblDisplayCreator.Text;
            string label = lblDisplayLabel.Text;
            int categoryId = Convert.ToInt32(ddlCategory.SelectedValue);
            string priorityCode = ddlPriority.SelectedValue;
            string assignee = ddlAssigned.SelectedValue;
            string description = txtDescription.Text;
            int statusCode = Convert.ToInt32(ddlStatus.SelectedValue);
            string resolvedDate = txtDateResolved.Text;

            string connectionString =
                    WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

            SqlConnection con = new SqlConnection(connectionString);

            using (con)
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sprocUpdateIssue";

                try
                {
                    cmd.Parameters.Add(new SqlParameter("@iss_id", SqlDbType.Int));
                    cmd.Parameters["@iss_id"].Value = issueId;

                    cmd.Parameters.Add(new SqlParameter("@cat_id", SqlDbType.Int));
                    cmd.Parameters["@cat_id"].Value = categoryId;

                    cmd.Parameters.Add(new SqlParameter("@priority_code", SqlDbType.VarChar, 20));
                    cmd.Parameters["@priority_code"].Value = priorityCode;

                    cmd.Parameters.Add(new SqlParameter("@assign_id", SqlDbType.VarChar, 20));
                    cmd.Parameters["@assign_id"].Value = assignee;

                    cmd.Parameters.Add(new SqlParameter("@iss_desc", SqlDbType.VarChar, 1000));
                    cmd.Parameters["@iss_desc"].Value = description;

                    if (resolvedDate != String.Empty)
                    {
                        cmd.Parameters.Add(new SqlParameter("@iss_dateresolved", SqlDbType.DateTime));
                        cmd.Parameters["@iss_dateresolved"].Value = resolvedDate;
                    }

                    cmd.Parameters.Add(new SqlParameter("@status_code", SqlDbType.Int));
                    cmd.Parameters["@status_code"].Value = statusCode;

                    con.Open();
                    cmd.ExecuteNonQuery();

                    Session["AddMessage"] = "Issue successfully modified.";
                    Response.Redirect("~/View.aspx", true);
                }
                catch
                {
                    lblErrorStatus.Text = "There was an error modifying this issue.<br />";
                    lblErrorStatus.Visible = true;
                }
            }
        }
    }

    protected void btnDiscard_Click(object sender, EventArgs e)
    {
        Session["AddMessage"] = "Issue was not modified.";
        Response.Redirect("~/View.aspx");
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int issueId = Convert.ToInt32(lblDisplayId.Text);
        string connectionString =
                WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        SqlConnection con = new SqlConnection(connectionString);

        using (con)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sprocDeleteIssue";

            try
            {
                cmd.Parameters.Add(new SqlParameter("@iss_id", SqlDbType.Int));
                cmd.Parameters["@iss_id"].Value = issueId;

                con.Open();
                cmd.ExecuteNonQuery();

                Session["AddMessage"] = "Issue deleted.";
                Response.Redirect("~/View.aspx", true);
            }
            catch
            {
                lblErrorStatus.Text = "There was an error deleting this issue.<br />";
                lblErrorStatus.Visible = true;
            }
        }
    }
}
